package net.fdukedom.epicurus.presentation.actions.pub;

import net.fdukedom.epicurus.presentation.actions.AbstractAction;
import net.fdukedom.epicurus.domain.entity.User;
import net.fdukedom.epicurus.domain.util.UserHelper;
import net.fdukedom.epicurus.domain.util.GroupHelper;
import net.fdukedom.epicurus.tools.config.Configuration;
import net.fdukedom.epicurus.tools.config.Key;
import net.fdukedom.epicurus.tools.mail.MailServer;
import net.fdukedom.epicurus.tools.mail.MessageNotSentException;
import net.fdukedom.epicurus.messaging.MessageDispatcher;
import net.fdukedom.epicurus.messaging.Message;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Register action.
 *
 * @author Dmitry Y. Kochelaev
 * @author Sergey Vishnyakov
 */
public class RegisterAction extends AbstractAction<RegisterForm> {

    private UserHelper userHelper = UserHelper.getInstance();

    private GroupHelper groupHelper = GroupHelper.getInstance();

    private MessageDispatcher messageDispatcher = MessageDispatcher.getInstance();

    protected ActionForward doExecute(ActionMapping mapping, RegisterForm form, HttpServletRequest request, HttpServletResponse response) {
        User user = new User(form.getUserName(), form.getEmail(), User.hash(form.getPassword()));
        user.setSex(form.getSex());
        user.getGroups().add(groupHelper.findByName("allUsers"));
        user.getGroups().add(groupHelper.findByName("registeredUsers"));
        userHelper.saveUser(user);
        boolean isActivationRequired = Configuration.getInstance().getBooleanValue(Key.ACTIVATION_TURNED_ON);
        if (isActivationRequired) {
            try {
                new MailServer().sendActivatioEMail(user);
            } catch (MessageNotSentException e) {
                user.setIsActivated(true);
                userHelper.saveUser(user);
                isActivationRequired = false;
            }
        } else {
            user.setIsActivated(true);
            userHelper.saveUser(user);
        }
        messageDispatcher.send(new Message("core.userRegistered", user));
        return mapping.findForward(isActivationRequired ? "activate" : "success");
    }
}
